package com.min.netty.file;

import com.min.netty.file.constant.Constant;
import com.min.netty.file.constant.TransferFile;
import com.min.netty.file.handler.MinFileClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class MinFileClient {
    private final String host;
    private final int port;

    /**
     * Netty客户端
     *
     * @param host 连接地址
     * @param port 端口
     */
    public MinFileClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    /**
     * 上传文件
     *
     * @param file 传输文件DTO
     * @throws InterruptedException 线程异常
     * @throws IOException          IO异常
     */
    public void connect(final TransferFile file) throws InterruptedException, IOException {
        Path path = Paths.get(file.getFile().toURI());
        if (Files.notExists(path)) {
            throw new FileNotFoundException(path.toString());
        }
        if (Files.isDirectory(path)) {
            // 如果上传的不是文件，抛出异常
            throw new IOException(String.format(Constant.NOT_VALID_FILE, path.toString()));
        }
        if (!Files.isReadable(path)) {
            // 上传文件不可读，抛出异常
            throw new IOException(String.format(Constant.UNABLE_READ_FILE, path.toString()));
        }
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast(new ObjectEncoder());
                            ch.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE,
                                    ClassResolvers.weakCachingConcurrentResolver(null)));
                            ch.pipeline().addLast(new MinFileClientHandler(file));
                        }
                    });
            ChannelFuture f = b.connect(this.host, this.port).sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
